#include "ratingmanager.h"
#include <QMutexLocker>
#include <QDateTime>
#include <QRandomGenerator>
#include <QDebug>
#include <QTimer>

namespace RestaurantSystem {

// 静态成员初始化
RatingManager* RatingManager::s_instance = nullptr;

RatingManager::RatingManager(QObject* parent)
    : QObject(parent)
    , m_dataManager(nullptr)
    , m_isInitialized(false)
    , m_dataLoaded(false)
{
    m_dataManager = &DataManager::instance();
    
    // 连接数据变更信号
    connect(m_dataManager, &DataManager::externalFileChanged,
            this, &RatingManager::onExternalFileChanged);
}

RatingManager::~RatingManager()
{
    if (s_instance == this) {
        s_instance = nullptr;
    }
}

RatingManager& RatingManager::instance()
{
    if (!s_instance) {
        s_instance = new RatingManager();
    }
    return *s_instance;
}

bool RatingManager::initialize()
{
    QMutexLocker locker(&m_mutex);
    
    if (m_isInitialized) {
        return true;
    }
    
    if (!m_dataManager->initialize()) {
        LOG_ERROR("Failed to initialize DataManager", "RatingManager");
        return false;
    }
    
    if (!loadRatingData()) {
        LOG_ERROR("Failed to load rating data", "RatingManager");
        return false;
    }
    
    m_isInitialized = true;
    m_dataLoaded = true;
    

    return true;
}

QPair<RatingOperationResult, QString> RatingManager::createRating(const QString& orderId, 
                                                                 const QString& customerName,
                                                                 int rating, 
                                                                 const QString& comment)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isInitialized) {
        return qMakePair(RatingOperationResult::SYSTEM_ERROR, QString());
    }
    
    // 检查订单是否存在
    Order order = m_dataManager->getOrderById(orderId);
    if (order.id.isEmpty()) {
        return qMakePair(RatingOperationResult::ORDER_NOT_FOUND, QString());
    }
    
    // 检查是否已经评价过
    if (isOrderRated(orderId)) {
        return qMakePair(RatingOperationResult::ALREADY_RATED, QString());
    }
    
    // 创建评价对象
    Rating newRating(orderId, customerName, rating, comment);
    newRating.id = generateRatingId();
    
    // 验证评价数据
    ValidationResult validation = validateRating(newRating);
    if (!validation.isValid) {
        LOG_ERROR("Invalid rating data: " + validation.errorMessage, "RatingManager");
        return qMakePair(RatingOperationResult::INVALID_DATA, QString());
    }
    
    // 添加到缓存
    m_ratings.append(newRating);
    
    // 保存到文件
    if (!m_dataManager->addRating(newRating)) {
        // 如果保存失败，从缓存中移除
        m_ratings.removeLast();
        return qMakePair(RatingOperationResult::SYSTEM_ERROR, QString());
    }
    
    // 延迟发出信号，避免在持有mutex时发射信号导致死锁
    QTimer::singleShot(0, this, [this, newRating]() {
        emit ratingCreated(newRating);
        emit ratingsChanged();
    });
    
    return qMakePair(RatingOperationResult::SUCCESS, newRating.id);
}

QList<Rating> RatingManager::getAllRatings()
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    return m_ratings;
}

Rating RatingManager::getRatingById(const QString& id)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    for (const Rating& rating : m_ratings) {
        if (rating.id == id) {
            return rating;
        }
    }
    
    return Rating(); // 返回无效对象
}

Rating RatingManager::getRatingByOrderId(const QString& orderId)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    for (const Rating& rating : m_ratings) {
        if (rating.orderId == orderId) {
            return rating;
        }
    }
    
    return Rating(); // 返回无效对象
}

QList<Rating> RatingManager::getRatingsByCustomerName(const QString& customerName)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    QList<Rating> customerRatings;
    for (const Rating& rating : m_ratings) {
        if (rating.customerName == customerName) {
            customerRatings.append(rating);
        }
    }
    
    return customerRatings;
}

QList<Rating> RatingManager::searchRatings(const RatingSearchCriteria& criteria)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    QList<Rating> results;
    for (const Rating& rating : m_ratings) {
        if (matchesSearchCriteria(rating, criteria)) {
            results.append(rating);
        }
    }
    
    return results;
}

RatingOperationResult RatingManager::updateRating(const Rating& rating)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isInitialized) {
        return RatingOperationResult::SYSTEM_ERROR;
    }
    
    // 验证评价数据
    ValidationResult validation = validateRating(rating);
    if (!validation.isValid) {
        LOG_ERROR("Invalid rating data: " + validation.errorMessage, "RatingManager");
        return RatingOperationResult::INVALID_DATA;
    }
    
    // 查找并更新缓存中的评价
    for (int i = 0; i < m_ratings.size(); ++i) {
        if (m_ratings[i].id == rating.id) {
            Rating oldRating = m_ratings[i];
            m_ratings[i] = rating;
            
            // 保存到文件
            if (!m_dataManager->updateRating(rating)) {
                // 如果保存失败，恢复原数据
                m_ratings[i] = oldRating;
                return RatingOperationResult::SYSTEM_ERROR;
            }
            
            // 发出信号
            emit ratingUpdated(rating.id, oldRating, rating);
            emit ratingsChanged();
            
            return RatingOperationResult::SUCCESS;
        }
    }
    
    return RatingOperationResult::RATING_NOT_FOUND;
}

RatingOperationResult RatingManager::deleteRating(const QString& ratingId)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_isInitialized) {
        return RatingOperationResult::SYSTEM_ERROR;
    }
    
    // 查找并删除缓存中的评价
    for (int i = 0; i < m_ratings.size(); ++i) {
        if (m_ratings[i].id == ratingId) {
            Rating deletedRating = m_ratings[i];
            m_ratings.removeAt(i);
            
            // 从文件中删除
            if (!m_dataManager->deleteRating(ratingId)) {
                // 如果删除失败，恢复数据
                m_ratings.insert(i, deletedRating);
                return RatingOperationResult::SYSTEM_ERROR;
            }
            
            // 发出信号
            emit ratingDeleted(ratingId);
            emit ratingsChanged();
            
            return RatingOperationResult::SUCCESS;
        }
    }
    
    return RatingOperationResult::RATING_NOT_FOUND;
}

bool RatingManager::canRateOrder(const QString& orderId, const QString& customerName)
{
    QMutexLocker locker(&m_mutex);
    
    // 检查订单是否存在
    Order order = m_dataManager->getOrderById(orderId);
    if (order.id.isEmpty()) {
        return false;
    }
    
    // 通过用户名查找客户ID
    Customer customer = m_dataManager->getCustomerByUsername(customerName);
    if (customer.id.isEmpty()) {
        return false;
    }
    
    // 检查订单是否属于该顾客
    if (order.customerId != customer.id) {
        return false;
    }
    
    // 检查订单是否已完成
    if (order.status != OrderStatus::COMPLETED) {
        return false;
    }
    
    // 检查是否已经评价过
    if (isOrderRated(orderId)) {
        return false;
    }
    
    return true;
}

bool RatingManager::isOrderRated(const QString& orderId)
{
    // 注意：这个方法可能在已经持有mutex的情况下被调用，
    // 所以不能再次调用可能需要锁的方法
    // 如果数据未加载，直接返回false，让调用者处理
    
    for (const Rating& rating : m_ratings) {
        if (rating.orderId == orderId) {
            return true;
        }
    }
    
    return false;
}

ValidationResult RatingManager::validateRating(const Rating& rating)
{
    ValidationResult result;
    result.isValid = true;
    
    if (rating.orderId.isEmpty()) {
        result.isValid = false;
        result.errorMessage = "订单ID不能为空";
        return result;
    }
    
    if (rating.customerName.isEmpty()) {
        result.isValid = false;
        result.errorMessage = "顾客用户名不能为空";
        return result;
    }
    
    if (rating.rating < 1 || rating.rating > 5) {
        result.isValid = false;
        result.errorMessage = "评分必须在1-5之间";
        return result;
    }
    
    if (rating.comment.length() > 500) {
        result.isValid = false;
        result.errorMessage = "评价内容不能超过500字符";
        return result;
    }
    
    return result;
}

RatingStatistics RatingManager::getRatingStatistics(const QDateTime& startDate, 
                                                   const QDateTime& endDate)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    QList<Rating> filteredRatings;
    
    for (const Rating& rating : m_ratings) {
        bool includeRating = true;
        
        if (startDate.isValid() && rating.createdDate < startDate) {
            includeRating = false;
        }
        
        if (endDate.isValid() && rating.createdDate > endDate) {
            includeRating = false;
        }
        
        if (includeRating) {
            filteredRatings.append(rating);
        }
    }
    
    return calculateStatistics(filteredRatings);
}

RatingStatistics RatingManager::getCustomerRatingStatistics(const QString& customerName)
{
    QMutexLocker locker(&m_mutex);
    
    QList<Rating> customerRatings = getRatingsByCustomerName(customerName);
    return calculateStatistics(customerRatings);
}

QList<Rating> RatingManager::getRecentRatings(int limit)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    // 按创建时间排序
    QList<Rating> sortedRatings = m_ratings;
    std::sort(sortedRatings.begin(), sortedRatings.end(), 
              [](const Rating& a, const Rating& b) {
                  return a.createdDate > b.createdDate;
              });
    
    // 返回指定数量的最近评价
    if (limit > 0 && limit < sortedRatings.size()) {
        return sortedRatings.mid(0, limit);
    }
    
    return sortedRatings;
}

QList<Rating> RatingManager::getHighRatedRatings(int minRating, int limit)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_dataLoaded) {
        loadRatingData();
    }
    
    QList<Rating> highRatedRatings;
    for (const Rating& rating : m_ratings) {
        if (rating.rating >= minRating) {
            highRatedRatings.append(rating);
        }
    }
    
    // 按评分和时间排序
    std::sort(highRatedRatings.begin(), highRatedRatings.end(), 
              [](const Rating& a, const Rating& b) {
                  if (a.rating != b.rating) {
                      return a.rating > b.rating;
                  }
                  return a.createdDate > b.createdDate;
              });
    
    // 返回指定数量的高评分评价
    if (limit > 0 && limit < highRatedRatings.size()) {
        return highRatedRatings.mid(0, limit);
    }
    
    return highRatedRatings;
}

QString RatingManager::generateRatingId()
{
    return QString("RATING_%1_%2")
        .arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"))
        .arg(QRandomGenerator::global()->bounded(1000, 9999));
}

QString RatingManager::getOperationResultMessage(RatingOperationResult result)
{
    switch (result) {
    case RatingOperationResult::SUCCESS:
        return "操作成功";
    case RatingOperationResult::RATING_NOT_FOUND:
        return "评价不存在";
    case RatingOperationResult::ORDER_NOT_FOUND:
        return "订单不存在";
    case RatingOperationResult::ALREADY_RATED:
        return "该订单已经评价过";
    case RatingOperationResult::INVALID_DATA:
        return "数据无效";
    case RatingOperationResult::PERMISSION_DENIED:
        return "权限不足";
    case RatingOperationResult::SYSTEM_ERROR:
        return "系统错误";
    default:
        return "未知错误";
    }
}

QString RatingManager::formatRatingStars(int rating)
{
    if (rating < 1 || rating > 5) {
        return "无效评分";
    }
    
    QString stars;
    for (int i = 1; i <= 5; ++i) {
        if (i <= rating) {
            stars += "★";
        } else {
            stars += "☆";
        }
    }
    return stars;
}

QString RatingManager::getRatingLevelText(int rating)
{
    switch (rating) {
    case 5:
        return "非常满意";
    case 4:
        return "满意";
    case 3:
        return "一般";
    case 2:
        return "不满意";
    case 1:
        return "非常不满意";
    default:
        return "无效评分";
    }
}

void RatingManager::refreshRatingData()
{
    {
        QMutexLocker locker(&m_mutex);
        loadRatingData();
    } // 释放mutex锁
    
    // 在没有锁的情况下发射信号，避免死锁
    QTimer::singleShot(0, this, [this]() {
        emit ratingsChanged();
    });
}

void RatingManager::onExternalFileChanged(DataType dataType, const QString& filePath)
{
    if (dataType == DataType::RATINGS) {
        // 使用安全的延迟重载机制，避免死锁的同时保持实时性
        QTimer::singleShot(800, this, [this]() {
            safeReloadRatingData();
        });
    }
}

bool RatingManager::loadRatingData()
{
    if (!m_dataManager) {
        return false;
    }
    
    try {
        m_ratings = m_dataManager->getAllRatings();
        m_dataLoaded = true;

        return true;
    } catch (const std::exception& e) {
        LOG_ERROR(QString("Failed to load rating data: %1").arg(e.what()), "RatingManager");
        return false;
    }
}

bool RatingManager::saveRatingData()
{
    if (!m_dataManager) {
        return false;
    }
    
    try {
        // DataManager会自动处理保存，这里主要是触发保存操作
        return m_dataManager->saveAll();
    } catch (const std::exception& e) {
        LOG_ERROR(QString("Failed to save rating data: %1").arg(e.what()), "RatingManager");
        return false;
    }
}

bool RatingManager::matchesSearchCriteria(const Rating& rating, const RatingSearchCriteria& criteria)
{
    if (!criteria.customerName.isEmpty() && rating.customerName != criteria.customerName) {
        return false;
    }
    
    if (!criteria.orderId.isEmpty() && rating.orderId != criteria.orderId) {
        return false;
    }
    
    if (criteria.minRating >= 1 && rating.rating < criteria.minRating) {
        return false;
    }
    
    if (criteria.maxRating <= 5 && rating.rating > criteria.maxRating) {
        return false;
    }
    
    if (criteria.startDate.isValid() && rating.createdDate < criteria.startDate) {
        return false;
    }
    
    if (criteria.endDate.isValid() && rating.createdDate > criteria.endDate) {
        return false;
    }
    
    if (!criteria.keyword.isEmpty()) {
        if (!rating.comment.contains(criteria.keyword, Qt::CaseInsensitive)) {
            return false;
        }
    }
    
    return true;
}

RatingStatistics RatingManager::calculateStatistics(const QList<Rating>& ratings)
{
    RatingStatistics stats;
    stats.totalRatings = ratings.size();
    
    if (ratings.isEmpty()) {
        return stats;
    }
    
    // 初始化分布数组
    stats.ratingDistribution = QList<int>{0, 0, 0, 0, 0};
    
    double totalRating = 0.0;
    for (const Rating& rating : ratings) {
        totalRating += rating.rating;
        
        // 更新分布统计
        if (rating.rating >= 1 && rating.rating <= 5) {
            stats.ratingDistribution[rating.rating - 1]++;
            
            switch (rating.rating) {
            case 1: stats.oneStarCount++; break;
            case 2: stats.twoStarCount++; break;
            case 3: stats.threeStarCount++; break;
            case 4: stats.fourStarCount++; break;
            case 5: stats.fiveStarCount++; break;
            }
        }
    }
    
    stats.averageRating = totalRating / stats.totalRatings;
    stats.calculateSatisfactionRate();
    
    return stats;
}

void RatingManager::safeReloadRatingData()
{
    // 检查是否正在初始化或关闭
    if (!m_isInitialized) {
        return;
    }
    
    // 重新加载数据（不使用refreshRatingData避免信号冲突）
    {
        QMutexLocker locker(&m_mutex);
        bool success = loadRatingData();
        if (!success) {
            return;
        }
    } // 释放锁
    
    // 异步发射信号，确保不会死锁
    QTimer::singleShot(100, this, [this]() {
        emit ratingsChanged();
    });
}

} // namespace RestaurantSystem
